package org.addsome.leetcode;

import jdk.nashorn.internal.objects.annotations.ScriptClass;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 面试题 17.11. 单词距离
 * 有个内含单词的超大文本文件，给定任意两个单词，找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次，而每次寻找的单词不同，你能对此优化吗?
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/find-closest-lcci
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @author 14813
 * @date 2020/5/10
 **/
public class FindClosestLcci {

    private static int findClosest(String[] words, String word1, String word2) {
        String foundWord = null;
        String findingWord = null;
        int point = 0;
        int minDistance = 0;
        for (int i = 0; i < words.length; i++) {
            if (findingWord == null) {
                if (words[i].equals(word1)) {
                    foundWord = word1;
                    findingWord = word2;
                    point = i;
                } else if (words[i].equals(word2)) {
                    foundWord = word2;
                    findingWord = word1;
                    point = i;
                }
            } else {
                if (i - point == minDistance) {
                    findingWord = null;
                }
                if (words[i].equals(foundWord)) {
                    point = i;
                }
                if (words[i].equals(findingWord)) {
                    minDistance = i - point;
                    point = i;
                    String tmp = findingWord;
                    findingWord = foundWord;
                    foundWord = tmp;
                }
            }
        }
        return minDistance;
    }

    private static Map<String, List<Integer>> getMap(String[] words) {
        Map<String, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            map.putIfAbsent(words[i], new ArrayList<>());
            map.get(words[i]).add(i);
        }
        return map;
    }

    private static int findClosestMoreTime(String[] words, String word1, String word2) {
        Map<String, List<Integer>> map = getMap(words);
        List<Integer> l1 = map.get(word1);
        List<Integer> l2 = map.get(word2);
        int min = Integer.MAX_VALUE;
        int j = 0;
        for (Integer integer : l1) {
            if (l2.get(j) < integer) {
                while (j < l2.size() - 1 && l2.get(j + 1) < integer) {
                    j++;
                }
                min = Math.min(min, integer - l2.get(j));
                if (j < l2.size() - 1) {
                    min = Math.min(min, l2.get(j + 1) - integer);
                }
            } else {
                min = Math.min(min, l2.get(j) - integer);
            }
        }
        return min;
    }

    public static void main(String[] args) {
    }
}
